package com.air.common.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.air.common.vo.SubmitTokenVO;

public class SubmitTokenFactory {
	
	private static SubmitTokenFactory instance;
	
	
	public static SubmitTokenFactory getInstance(){
		if (instance==null){
			instance = new SubmitTokenFactory();
		}
		return instance;
	}
	
	@SuppressWarnings("unchecked")
	synchronized public SubmitTokenVO applyNewToken(HttpServletRequest request){
		
		HttpSession session = request.getSession();
		
		SubmitTokenVO token = new SubmitTokenVO();
		String issuer = request.getRequestURI();
		String value = CommonUtil.randomString(10)+System.currentTimeMillis();
		long   issueDate = System.currentTimeMillis();
		token.setIssuer(issuer);
		token.setValue(value);
		token.setIssueDate(issueDate);
		
		List<SubmitTokenVO> tokenList;
		
		if (session.getAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN_LIST)==null){
			tokenList = new ArrayList<SubmitTokenVO>();
		}else{
			tokenList = (List<SubmitTokenVO>) session.getAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN_LIST);
		}
		tokenList =  updateOrAddToken(tokenList,token);
		session.setAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN_LIST, tokenList);
		
		
		return token;
	}
	
	synchronized protected List<SubmitTokenVO> updateOrAddToken(List<SubmitTokenVO> tokenList,SubmitTokenVO newToken){
		
		for(SubmitTokenVO token:tokenList){
			if (token.getIssuer().equals(newToken.getIssuer())){
				tokenList.remove(token);
				break;
			}
		}
		tokenList.add(newToken);
		
		return tokenList;
	}
	
	@SuppressWarnings("unchecked")
	synchronized public boolean isValidToken(HttpServletRequest request,String issuer,String value){
		boolean isValid = false;
		
		HttpSession session = request.getSession();
		if (session.getAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN_LIST)==null){
			return false;
		}
		List<SubmitTokenVO> tokenList = (List<SubmitTokenVO>) session.getAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN_LIST);
		
		for(SubmitTokenVO token:tokenList){
			if (token.getIssuer().equals(issuer)&&token.getValue().equals(value)){
				isValid = true;
				tokenList.remove(token);
				break;
			}
		}
		session.setAttribute(BasicAppConstant._KEY_SUBMIT_TOKEN_LIST, tokenList);
		return isValid;
	}
	
	protected void removeExpiredToken(){
		//TODO
	}
	
}
